package com.joinval.modules.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.druid.wall.WallFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joinval.common.exception.JoinvalException;
import com.joinval.modules.sys.entity.SysDictItem;
import com.joinval.modules.sys.service.SysDictItemService;
import com.joinval.stamp.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.joinval.modules.sys.entity.SysDict;
import com.joinval.modules.sys.service.SysDictService;
import com.joinval.common.utils.PageUtils;
import com.joinval.common.utils.Result;

import javax.validation.Valid;


/**
 * 字典表
 */

@Api(description = "字典表")
@RestController
@RequestMapping("sys/sysDict")
public class  SysDictController {

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysDictItemService sysDictItemService;

    /**
     * 列表
     */
    @ApiOperation(value="列表")
    @GetMapping("/list")
    public Result list(@RequestParam Map<String, Object> params){
        PageUtils page = sysDictService.queryPage(params);
        return Result.ok().data(page);
    }
    /**
     * 列表
     */
    @ApiOperation(value="字典项明细")
    @GetMapping("/listDictItem")
    public Result listDictItem(@RequestParam Map<String, Object> params){
        if (!(params.containsKey("dictCode")&& StringUtils.isNotEmpty(MapUtils.getString(params,"dictCode")))){
            throw new JoinvalException("缺少参数【dictCode】或参数【dictCode】为空");
        }
        PageUtils page = sysDictItemService.queryPage(params);
        return Result.ok().data(page);
    }


    /**
     * 信息
     */
    @ApiOperation(value="信息")
    @GetMapping("/info/{sysDictId}")
    public Result info(@PathVariable("sysDictId") Long sysDictId){
		SysDict sysDict = sysDictService.getById(sysDictId);
        return Result.ok().data(sysDict);
    }

    /**
     * 新增
     */
    @ApiOperation(value="新增")
    @PostMapping("/save")
    public Result save(@RequestBody @Valid SysDict sysDict){
        checkDictCode(sysDict);
        Boolean result = sysDictService.save(sysDict);
        return result?Result.ok():Result.error("保存失败");
    }

    /**
     * 修改
     */
    @ApiOperation(value="修改")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid SysDict sysDict){
        checkDictCode(sysDict);
        Boolean result = sysDictService.updateById(sysDict);
        return result?Result.ok():Result.error("更新失败");
    }

    /**
     * 删除
     */
    @ApiOperation(value="删除")
    @PostMapping("/delete/{sysDictId}")
    public Result delete(@PathVariable("sysDictId") Long sysDictId){
		Boolean result = sysDictService.removeById(sysDictId);
        return result?Result.ok():Result.error("删除失败");
    }

    /**
     * 字典明细列表
     */
    @ApiOperation(value="字典明细列表")
    @GetMapping("/listItem/{dictCode}")
    public Result listItem(@PathVariable String dictCode){
        List<SysDictItem> list = sysDictItemService.list(new QueryWrapper<SysDictItem>().lambda().eq(SysDictItem::getDictCode, dictCode));
        List<Map<String, Object>> itemlist = null;
        if(CollectionUtils.isNotEmpty(list)){
            itemlist = list.stream().map(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("itemText", item.getItemText());
                map.put("itemValue", item.getItemValue());
                return map;
            }).collect(Collectors.toList());
        }
        return Result.ok().data(itemlist);
    }

    /**
     * 字典明细新增
     */
    @ApiOperation(value="字典明细新增")
    @PostMapping("/saveItem")
    public Result saveItem(@RequestBody @Valid SysDictItem sysDictItem){
        checkDictItemCode(sysDictItem);
        Boolean result = sysDictItemService.save(sysDictItem);
        return result?Result.ok():Result.error("保存失败");
    }

    /**
     * 字典明细修改
     */
    @ApiOperation(value="字典明细修改")
    @PostMapping("/updateItem")
    public Result updateItem(@RequestBody @Valid SysDictItem sysDictItem){
        checkDictItemCode(sysDictItem);
        Boolean result = sysDictItemService.updateById(sysDictItem);
        return result?Result.ok():Result.error("更新失败");
    }

    /**
     *字典明细删除
     */
    @ApiOperation(value="字典明细删除")
    @PostMapping("/deleteItem/{sysDictItemId}")
    public Result deleteItem(@PathVariable("sysDictItemId") Long sysDictItemId){
        Boolean result = sysDictItemService.removeById(sysDictItemId);
        return result?Result.ok():Result.error("删除失败");
    }


    void checkDictCode(SysDict dict){
        List<SysDict> listSysDict = sysDictService.list(new QueryWrapper<SysDict>().lambda().eq(SysDict::getDictCode,dict.getDictCode()));
        if(CollectionUtils.isNotEmpty(listSysDict)){
            if(dict.getSysDictId() == null){
                throw new RuntimeException("字典code:" + dict.getDictCode() + ",已存在！");
            }
            for (SysDict sysDict : listSysDict) {
                  if(!dict.getSysDictId().equals(sysDict.getSysDictId())) {
                      throw new RuntimeException("字典code:" + dict.getDictCode() + ",已存在！");
                  }
            }
        }
    }

    void checkDictItemCode(SysDictItem dictItem){
        List<SysDictItem> listSysDictItem = sysDictItemService.list(
                new QueryWrapper<SysDictItem>().lambda().
                        eq(SysDictItem::getDictCode,dictItem.getDictCode()).
                        eq(SysDictItem::getItemValue,dictItem.getItemValue())
                );
        if(CollectionUtils.isNotEmpty(listSysDictItem)){
            if(dictItem.getSysDictItemId() == null){
                throw new RuntimeException("字典code:" + dictItem.getDictCode() + "字典项值:" + dictItem.getItemValue() + ",已存在！");
            }
            for (SysDictItem sysDictItem : listSysDictItem) {
                if(!dictItem.getSysDictItemId().equals(sysDictItem.getSysDictItemId())) {
                    throw new RuntimeException("字典项值:" + dictItem.getItemValue() + ",已存在！");
                }
            }
        }
    }

}
